#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpServer.h>
#include <iostream>
#include <unordered_map>
#include <string>
class DirctServer
{
public:
    DirctServer(int port):
    _server(&_baseloop,muduo::net::InetAddress("0.0.0.0",port),"DictServer",muduo::net::TcpServer::kReusePort)
    {
        _server.setConnectionCallback(std::bind(&DirctServer::onConnection,this,std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DirctServer::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    void start()
    {
        //先开始监听再开始循环
        _server.start();
        _baseloop.loop();
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr& con)
    {
        if(con->connected())
        {
            std::cout<<"connected success \n";
        }
        else
        {
            std::cout<<"connected failed \n";
        }
    }
    void onMessage(const muduo::net::TcpConnectionPtr& con,muduo::net::Buffer* buf,muduo::Timestamp t)
    {
        std::string msg = buf->retrieveAllAsString();
        std::string res;
        res=translate(msg);
        con->send(res);
    }

    std::string translate(const std::string& msg)
    {
        std::unordered_map<std::string,std::string>dict_map={
            {"hello","你好"},
            {"bit","比特"},
            {"world","世界"}
        };
        auto it=dict_map.find(msg);
        if(it==dict_map.end())   return "Unknown";
        return it->second;
    }
private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;

};
int main()
{
    DirctServer server(9090);
    server.start();
    return 0;
}